package com.smzd.framework.sso;

import java.util.ArrayList;
import java.util.List;

import com.renren.api.RennClient;
import com.renren.api.service.BasicInformation;
import com.renren.api.service.Sex;
import com.smzd.framework.sso.domain.SocialUser;
import com.smzd.framework.system.domain.UserBind;
import com.smzd.utils.httpclient.Client;
import com.smzd.utils.httpclient.Request;

public class RenrenOAuth2AuthenticationProcessor extends OAuth2AuthenticationProcessor {

    public final static String state = "renren";
    public final static String redirect_uri = "http://www.orimuse.com/sso/xtwl_getticket?state=" + state;
    // 人人网的OAuth2.0的token endpoint
    public final static String rrOAuthTokenEndpoint = "https://graph.renren.com/oauth/token";
    // 人人网的OAuth2.0的授权地址
    public final static String rrOAuthAuthorizeEndpoint = "https://graph.renren.com/oauth/authorize";

    private String appId = "269968";
    private String apiKey = "006be2e4608646019169b45a8d16e40a";
    private String apiSecret = "11e4e994fbe14c6fab4cacadba908466";

    public RenrenOAuth2AuthenticationProcessor() {
        super(state);
        this.platform = UserBind.AUTH_TYPE_RENREN;
    }

    @Override
    public Object getAccessToken(String queryString) throws Exception {
        String qs[] = queryString.split("&");
        String code = null;
        for (int i = 0; i < qs.length; i++) {
            if (qs[i].startsWith("code")) {
                code = qs[i].split("=")[1];
                break;
            }
        }
        System.out.println("code:" + code);

        RennClient rc = new RennClient(apiKey, apiSecret);
        rc.authorizeWithAuthorizationCode(code, redirect_uri);
        return rc;
    }

    @Override
    public Object getRemoteUserInfo(Object renrenClient) throws Exception {
        RennClient rc = (RennClient) renrenClient;

        com.renren.api.service.User remoteUser = rc.getUserService().getUserLogin();
        // Integer[] friendIds =
        // rc.getFriendService().listFriend(remoteUser.getId(), 500, 1);

        return remoteUser;
    }

    @Override
    public SocialUser convertRemoteToSocialUser(Object remoteUserInfo) throws Exception {
        com.renren.api.service.User remoteUser = (com.renren.api.service.User) remoteUserInfo;

        SocialUser user = new SocialUser();
        user.setAccessToken(null);
        user.setPlatform(this.getPlatform());
        user.setName(remoteUser.getName());
        user.setPassword(String.valueOf(remoteUser.getId()));
        user.setOpenid(user.getPassword());
        StringBuffer sb = new StringBuffer();
        sb.append("openid: ").append(remoteUser.getId());
        user.setDescription(sb.toString());

        try {
            BasicInformation bi = remoteUser.getBasicInformation();
            Sex sex = bi.getSex();
            user.setGender(sex == Sex.FEMALE ? 0 : 1);
        } catch (Exception e) {

        }

        return user;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    public String getApiSecret() {
        return apiSecret;
    }

    public void setApiSecret(String apiSecret) {
        this.apiSecret = apiSecret;
    }

    @Override
    public String getAuthenticationURL() throws Exception {
        String url = "https://graph.renren.com/oauth/authorize";
        Request request = new Client().GET(url).addParameter("client_id", appId)
                .addParameter("redirect_uri", redirect_uri).addParameter("response_type", "code");
        try {
            url = request.getHttpRequest().getURI().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    @Override
    public List<String> getFriendOpenids(SocialUser socialUser, Object accessToken) throws Exception {
        String openId = socialUser.getOpenid();
        Long userId = Long.parseLong(openId);
        RennClient rc = (RennClient) accessToken;
        Integer[] openIdArr = rc.getFriendService().listFriend(userId, 500, 1);
        List<String> openIdList = new ArrayList<>(30);
        if (openIdArr != null && openIdArr.length > 0) {
            for (Integer openid : openIdArr) {
                openIdList.add(String.valueOf(openid));
            }
        }
        return openIdList;
    }

}
